package mya_dc.compilation_server.threads;

import mya_dc.compilation_server.gui.CompilationServerGUI;
import mya_dc.shared_classes.Transmitter;

/**
 * Thread to maintain connection to the Master Server.
 * 
 * @author      Marina Skarbovsky
 * <br>			MYA
 */
public class MainServerConnectionThread implements Runnable
{
	public MainServerConnectionThread(CompilationServerGUI GUI)
	{
		m_GUI = GUI;
		m_bRunChecks = true;
	}

	
	/**
	 * Runs the MainServerConnectionThread that's responsible to maintain the connection with Master Server
	 *
	 */
	@Override
	public void run()
	{
		while (getRunChecks())
		{
			try
			{
				Thread.sleep(m_nSleepTime);
				Transmitter MainServerTransmitter = m_GUI.getCompilationServerRef().getMainServerTransmitter();
				if (MainServerTransmitter == null)
				{
					continue;
				}
				if (!MainServerTransmitter.isConnected())
				{
					if (!m_GUI.isReconnecting())
					{
						m_GUI.reconnect(); 
						try 
						{ 
							synchronized (this) {
								wait();
							}
						}
						catch (Exception e) {}
					}
				}
			} 
			catch (InterruptedException e) {}
		}
	}
	
	
	/**
	 * Sets a flag which signals the Thread whether to keep running, or terminate.
	 * 
	 * @param bRunChecks - Boolean flag.
	 */
	public static synchronized void setRunChecks(boolean bRunChecks)
	{
		m_bRunChecks = bRunChecks;
	}
	
	
	/**
	 * Gets the current value of the flag which signals the Thread whether to keep running, or terminate.
	 * 
	 * @param bRunChecks - Boolean flag.
	 */
	public static synchronized boolean getRunChecks()
	{
		return m_bRunChecks;
	}
	
	/**
	 * Sets the time interval between reconnection attempts.
	 * 
	 *  @param nNewSleepTime - Time interval in milliseconds.
	 * 
	 */
	public static void setSleepTime(int nNewSleepTime)
	{
		m_nSleepTime =  nNewSleepTime;
	}
	
	/**
	 * Gets the current value of the time interval between reconnection attempts.
	 * 
	 * 
	 */
	public static int getSleepTime()
	{
		return m_nSleepTime;
	}
	
	
	//Members
	private CompilationServerGUI m_GUI = null;
	private static int m_nSleepTime = 10000;
	private static  boolean m_bRunChecks;
}